<?php

namespace  Inter\ArticleBundle\Service;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Doctrine\ORM\EntityManager;
use Inter\ArticleBundle\Entity\User;
use Symfony\Component\DependencyInjection\Container;




class Common
{
	private $templating;
	
	private $router;
	
	private $em;
	
	private $container;
	
	public function __construct(EngineInterface $templating, 
					UrlGeneratorInterface $router, EntityManager $em, Container $container )
	{
		$this->templating = $templating;
		$this->router = $router;
		$this->em = $em;
		$this->container = $container;
		
	}
	
	public function getDemo(Request $request,User $user)
	{
		if ($request->isMethod('POST')) {
			// .. do some things
	
			$url = $this->router->generate('homepage');
			return new RedirectResponse($url);
		}
	
		
		
		$result = $this->em->createQueryBuilder()
		->select('a')
		->from('InterArticleBundle:Article',  'a')
		->where('a.author = ?1')
		->addOrderBy('a.createdat', 'DESC')
		->setParameter('1', $user->getId())
		->getQuery()
		->getResult()
		;
		
		$cache_key = 'article_cache_admin_listarticle';
		$cache = $this->container->get('liip_doctrine_cache.ns.interarticle');
		
		if (false === ($cached_data = $cache->fetch($cache_key))) {
			$cached_data = $result;
			$cache->save($cache_key, $cached_data, 3600);//TTL 1h
		}
		 
		 
		$paginator  = $this->container->get('knp_paginator');
		$pagination = $paginator->paginate(
				$cached_data,
				$request->query->get('page', 1)/*page number*/,
				5/*limit per page*/
		);
		
		return $pagination;
		
		
		
	}
}